#菜单管理
from flask import Blueprint,request,jsonify
from flaskDemo.sql.mysql_db import mysql_db
from flaskDemo.extensions.success import list_result
from flaskDemo.extensions.error import CustomExcetion
from flaskDemo.config.config import Config
from flaskDemo.sql.sqlModel import SqlModel
menu = Blueprint('menu',__name__)
err = Config.ERR

@menu.route("/getRouteList")
def getRouteList():
    params = request.values
    menuType = params.get("menuType")
    roleIds = params.get("roleIds")
    with mysql_db() as db:
        sql = f"select * from system_menu where menu_type = {menuType} and pid = '0'"
        result = db.fetch_all(sql)
        def circulate_child(item, pidArr):
            sql = f"select * from system_menu where pid = '{item['id']}' and menu_type = {menuType}"
            child_result = db.fetch_all(sql)
            if len(child_result) > 0:
                item["children"] = list(filter(lambda n: n["id"] in pidArr, child_result))
                for itemChild in child_result:
                    circulate_child(itemChild, pidArr)
            else:
                item["children"] = []

        if len(result) > 0:
            pidArr = getIsShowMenu(roleIds)
            newList = list(filter(lambda n: n["id"] in pidArr, result))
            for item in newList:
                if item["child_menu_show"] == 1:
                    item["children"] = []
                else:
                    circulate_child(item, pidArr)
            return list_result(newList)
        else:
            raise CustomExcetion(err["1005"][0], err["1005"][1])


# 获取用户角色的所有查看权限
def getIsShowMenu(roleIds):
    with mysql_db() as db:
        sql = f"select DISTINCT a.menu_id,a.role_id,b.permissions,b.id_path  from system_role_menu a left join system_menu b on a.menu_id = b.id  where FIND_IN_SET(a.role_id,'{roleIds}') and b.permissions like '%%show'"
        result = db.fetch_all(sql)
        pidArr = map(lambda n: n["id_path"].split(","), result)
        pidList = set(list(sum(list(pidArr), [])))
        return pidList

@menu.route("/getMenuAllList")
def getMenuAllList():
    params = request.values
    with mysql_db() as db:
        sql = f"select * from system_menu where pid = '0'"
        result = db.fetch_all(sql)

        def circulate_child(item):
            sql = f"select * from system_menu where pid = '{item['id']}'"
            child_result = db.fetch_all(sql)
            if len(child_result) > 0:
                item["children"] = child_result
                for itemChild in child_result:
                    itemChild["children"] = getPermissionList(itemChild)
                    circulate_child(itemChild)
            else:
                item["children"] = getPermissionList(item)
                return -1

        if len(result) > 0:
            for item in result:
                item["children"] = getPermissionList(item)
                circulate_child(item)

        return list_result(result)


def getPermissionList(item):
    with mysql_db() as db:
        sql = f"select * from system_menu where pid = '{item['id']}'"
        btn_result = db.fetch_all(sql)
        return btn_result


@menu.route("/addOrUpdMenu",methods=["post"])
def addOrUpdMenu():
    params = request.json
    id = params.get("id")
    with mysql_db() as db:
        if id is not None and id != '':
            model = SqlModel("system_menu", [params])
            sql = model.update_sql()
            sql = f"{sql} where id = '{id}'"
            db.update(sql)
            db.conn.commit()
            res = list_result()
            return res
        else:
            model = SqlModel("system_menu", [params])
            sql = model.insert_sql()
            db.insert(sql)
            db.conn.commit()
            return list_result()

@menu.route("/deleteMenu",methods=["delete"])
def deleteMenu():
    params = request.values
    id = params["id"]
    model = SqlModel("system_menu", [params])
    sql = model.delete_sql()
    sql = f"{sql} where id = '{id}' or find_in_set(id_path,'{id}');"
    with mysql_db() as db:
        db.delete(sql)
        db.conn.commit()
        return list_result()
